package info.liuxing.okhttp.interceptor;

import info.liuxing.okhttp.config.RequestTag;
import info.liuxing.okhttp.config.TimeoutConfig;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.Objects;

/**
 * 动态设置超时时间
 *
 * @author liuxing (SE)
 * @summary 动态设置超时时间
 * @Copyright (c) 2017, Lianjia Group All Rights Reserved.
 * @since 2017-11-30 16:13
 */
public class DynamicSetTimeoutInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        if (Objects.isNull(request.tag()) || request.tag() instanceof Request) {
            return chain.proceed(request);
        }

        RequestTag tag = (RequestTag) request.tag();
        if (Objects.isNull(tag.getTimeout())) {
            return chain.proceed(request);
        }

        TimeoutConfig.Timeout timeout = tag.getTimeout();
        chain = chain.withConnectTimeout(timeout.getConnectTimeout(), timeout.getUnit())
                .withReadTimeout(timeout.getReadTimeout(), timeout.getUnit())
                .withWriteTimeout(timeout.getWriteTimeout(), timeout.getUnit());

        return chain.proceed(request);
    }

}
